var express = require('express');
var router = express.Router();
const { createAlipayPagePay } = require('./alipay.service');
const axios = require('axios');
const querystring = require('querystring');
const crypto = require('crypto');
const { Base64 } = require('js-base64');
const app = express();


// 快递鸟 API 配置
const EBusinessID = '1874372';  // 替换为你的 EBusinessID
const AppKey = 'd5659c30-a2c2-4883-876f-cf02339e166b';  // 替换为你的 AppKey


// 快递鸟的接口 URL
const API_URL = 'https://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx';

// 生成签名的方法（根据快递鸟文档）
const generateDataSign = (requestData) => {
    const md5 = crypto.createHash('md5');
    md5.update(requestData + AppKey);
    return Base64.encode(md5.digest('hex'));
};


//沙箱支付接口
router.post('/alipay', async (req, res) => {
    try {
        const orderData = req.body;
        const result = await createAlipayPagePay(orderData);
        console.log(result, "result");
        res.send(result);
    } catch (error) {
        console.error(error);
        res.status(500).send('支付请求失败');
    }
});


// 解析请求数据并准备发送
const getRequestData = (logisticsCode, trackingNumber) => {
    const requestData = JSON.stringify({
        ShipperCode: logisticsCode,  // 快递公司编码
        LogisticCode: trackingNumber, // 运单号
        RequestType: 8003,
    });

    const data = {
        RequestData: requestData,
        EBusinessID: EBusinessID,
        AppKey: AppKey,
        RequestType: 8003,  // 请求类型，8002 为物流跟踪
        DataSign: generateDataSign(requestData),
        DataType: '2'  // 返回格式，2 为 JSON 格式
    };

    return data;
};

// 查询物流轨迹的路由
router.get('/track', async (req, res) => {
    //   const { logisticsCode, trackingNumber } = req.query;
    const logisticsCode = req.query.logisticsCode
    const trackingNumber = req.query.trackingNumber
    console.log(logisticsCode, trackingNumber)

    // 准备请求数据
    const requestData = getRequestData(logisticsCode, trackingNumber);

    // 将请求数据转为 application/x-www-form-urlencoded 格式
    const postData = querystring.stringify(requestData);

    try {
        // 发起请求，设置表单数据编码格式
        const response = await axios.post(API_URL, postData, {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
            }
        });

        // 处理响应
        if (response.data && response.data.Status === 200) {
            res.json(response.data);  // 返回查询结果
        } else {
            res.status(200).json({ error: '查询', details: response.data });
        }
    } catch (error) {
        res.status(500).json({ error: '请求失败', details: error.message });
    }
});

const request = require('request')
const { randomCode, sendCode } = require("./getMessage");
const jwt = require('jsonwebtoken')
var { UserModel, ListModel } = require('../model/model')
const accessTokenSecret = 'your_access_token_secret';
const refreshTokenSecret = 'your_refresh_token_secret';
function generateAccessToken(user) {
    return jwt.sign({ user }, accessTokenSecret, { expiresIn: '10s' });
}
function generateRefreshToken(user) {
    return jwt.sign({ user }, refreshTokenSecret, { expiresIn: '7d' });
}
//验证短token是否过期
function verifyAccessToken(token) {
    try {
        return jwt.verify(token, accessTokenSecret);
    } catch (err) {
        return null;
    }
}

//验证长token是否过期
function verifyRefreshToken(token) {
    try {
        return jwt.verify(token, refreshTokenSecret);
        console.log('refreshToken过期');
    } catch (err) {
        return null;
    }
}
//重新获取获取access_token

router.post('/refresh_token', (req, res) => {
    // 获取refresh_token
    const refreshToken = req.body.refresh_token;
    // 验证refresh_token是否过期
    const user = verifyRefreshToken(refreshToken);
    if (user) {
        //如果长token还在 生成新的access_token
        const newAccessToken = generateAccessToken(user);
        res.json({ access_token: newAccessToken });
    } else {
        res.status(401).json({ message: 'Invalid refresh token' });
    }
});




//登录接口
router.post('/login', async (req, res) => {
    console.log('111111');

    const { username, password } = req.body; // 直接解构请求体
    console.log(username, password);

    let user = await UserModel.findOne({ phone: username }); // 根据用户名查找用户
    if (!user) {
        return res.status(200).send({ message: '账号错误', code: 1 }); // 账号不存在
    }
    if (user.password !== password) { // 验证密码
        return res.status(200).send({ message: '密码错误', code: 2 });
    }
    const accessToken = generateAccessToken(user.username); // 生成access_token
    const refreshToken = generateRefreshToken(user.username); // 生成refresh_token
    console.log("accessToken", accessToken, refreshToken);

    console.log("user", user);
    res.status(200).send({
        data: user,
        accessToken,
        refreshToken,
        message: '登录成功',
        code: 200,
    });
});

// 人脸登录验证识别接口
router.post("/face", async (req, res) => {
    const AK = "DG59594sEPgblOCdiJpiEWZH"
    const SK = "Jk0pmbByejKjITb2TQ6MH2gYdxIbEIdh"
    const usermodel = await UserModel.find();
    console.log(usermodel);
    const { imageData } = req.body;
    var options = {
        'method': 'POST',
        'url': 'https://aip.baidubce.com/rest/2.0/face/v3/search?access_token=' + await getAccessToken(),
        'headers': {
            'Content-Type': 'application/json'
        },
        data: JSON.stringify({
            "group_id_list": "xmface",
            "image": imageData,
            "image_type": "BASE64"
        })

    };
    axios(options)
        .then(response => {
            if (response.data.error_code === 0) {
                if (response.data.result.user_list[0].score >= 60) {
                    console.log(user);
                    res.send({
                        code: 200,
                        msg: "人脸识别成功",
                    })
                } else {
                    res.send({ code: 401, message: '人脸识别失败' })
                }
            } else {
                res.send({ code: 401, message: '人脸识别失败' })
            }
        }).catch(error => {
            res.send({ code: 401, msg: '检测不到人脸' })
        })
    /**
     * 使用 AK，SK 生成鉴权签名（Access Token）
     * @return string 鉴权签名信息（Access Token）
     */

    function getAccessToken() {
        let options = {
            'method': 'POST',
            'url': 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + AK + '&client_secret=' + SK,
        }
        return new Promise((resolve, reject) => {
            axios(options)
                .then(res => {
                    resolve(res.data.access_token)
                })
                .catch(error => {
                    reject(error)
                })
        })
    }
})
function getdata(id) {
    console.log(id);
}
//添加寄件地址
router.post('/add', async (req, res) => {
    const data = req.body;
    await Address1Model.create(data);
    res.send({ code: 200, msg: '添加成功' })
})

router.get('/address1', async (req, res) => {
    const id = req.query.user
    const data = await Address1Model.find({ user_id: id })
    res.send({
        data
    })
})


router.get("/login1", (req, res) => {
    const phone = req.query.phone;
    // console.log(phone);
    let code = randomCode(4);//生成6位数字随机验证码
    // console.log(code);
    sendCode(phone, code, function (success) {
        if (success) {
            res.send({
                code: 200,
                msg: "短信验证码发送成功",
                num: code
            });
        } else {
            res.send("短信验证码发送失败");
        }
    })
})
router.post('/add', async (req, res) => {
    const data = req.body;
    await Address1Model.create(data);
    res.send({ code: 200, msg: '添加成功' })
})
router.get('/address1', async (req, res) => {
    const id = req.query.user
    const data = await Address1Model.find({ user_id: id })
    res.send({
        data
    })
})
router.post('/add1', async (req, res) => {
    const data = req.body;
    await Address2Model.create(data);
    res.send({ code: 200, msg: '添加成功' })
})

router.get('/address2', async (req, res) => {
    const id = req.query.user
    const data = await Address2Model.find({ user_id: id })
    res.send({
        data
    })
})


router.get("/list", async (req, res) => {

    // console.log(token,'dddddd1');
    res.send({ code: 200, msg: "gggggg" })
})

// 启动 Express 服务
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});














var { UserModel, ListModel } = require('../model/model')
//人脸登录验证识别接口
router.post("/face", async (req, res) => {
    const AK = "DG59594sEPgblOCdiJpiEWZH"
    const SK = "Jk0pmbByejKjITb2TQ6MH2gYdxIbEIdh"

    const { imageData } = req.body;

    var options = {
        'method': 'POST',
        'url': 'https://aip.baidubce.com/rest/2.0/face/v3/search?access_token=' + await getAccessToken(),
        'headers': {
            'Content-Type': 'application/json'
        },
        // image 可以通过 getFileContentAsBase64("C:\fakepath\download.png") 方法获取,
        data: JSON.stringify({
            "group_id_list": "xmface",
            "image": imageData,
            "image_type": "BASE64"
        })

    };
    axios(options)
        .then(response => {
            console.log(response.data, '222222222222222222222222222222222');
            console.log(response.data.result.user_list[0]);
            console.log(response.data.result);
            if (response.data.error_code === 0) {
                if (response.data.result.user_list[0].score >= 80) {
                    res.send({
                        code: 200,
                        msg: "人脸识别成功",
                        name_id: response.data.result.user_list[0].user_id

                    })
                } else {
                    res.send({ code: 401, message: '人脸识别失败' })
                }
            } else {
                res.send({ code: 401, message: '人脸识别失败' })
            }
        }).catch(error => {
            res.send({ code: 401, msg: '检测不到人脸' })
        })
    /**
     * 使用 AK，SK 生成鉴权签名（Access Token）
     * @return string 鉴权签名信息（Access Token）
     */

    function getAccessToken() {

        let options = {
            'method': 'POST',
            'url': 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + AK + '&client_secret=' + SK,
        }
        return new Promise((resolve, reject) => {
            axios(options)
                .then(res => {
                    resolve(res.data.access_token)
                })
                .catch(error => {
                    reject(error)
                })
        })
    }
})


router.post("/list", async (req, res) => {
    console.log(req.body);
    res.send(req.body)
})
module.exports = router;
